﻿using System;
using System.IO;
using System.Web;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.ImageHandler;

namespace BikeBouncer.Site
{
	public class UploadManager
	{
		#region Pictures

		public static void SavePicture(Item item, HttpPostedFile file)
		{
			String pathOriginal = Settings.ItemPicturesPath + item.Id + ".original" + Path.GetExtension(file.FileName); 
			String path = Settings.ItemPicturesPath + item.Id + ".jpg";
			Stream contents = file.InputStream;

			if (contents.Length < 10 || item.Id < 1)
			{
				return;
			}

			file.SaveAs(pathOriginal);

			contents.Seek(0, SeekOrigin.Begin);

			Image img = new Image(contents);
			
			if (img.Width > 400 || img.Height > 300)
			{
				img.ResizeWithinDimensions(400, 300);
			}

			SaveExif(img, item);
			img.SaveJpg(path, 88);

			img.Dispose();
		}

		#endregion

		#region Helpers

		private static void SaveExif(Image img, Item item)
		{
			try
			{
				Exif.SetPropertyString(img.BitmapObject, (Int32)ExifTagNames.ImageDescription, Settings.ExifTitle + " - " + item.Id);
				Exif.SetPropertyString(img.BitmapObject, (Int32)ExifTagNames.ExifUserComment, Settings.ExifCopyright);
			}
			catch (Exception ex)
			{
				ErrorManager.Log(ex, "Problem setting EXIF on uploaded image.");
			}
		}

		#endregion
	}
}